<script setup>
import { invoke } from "@tauri-apps/api/core";
import { register, unregister } from '@tauri-apps/plugin-global-shortcut';
import { debounce } from 'lodash'
import { random as getRandom, sleep } from 'solar'
import Input from '@/components/common/Input.vue'
import Button from '@/components/common/Button.vue'
import { autoClick } from "@/native";
onMounted(async () => {
  console.log('onMounted')
  await registerKey()
});
const registerKey = async () => {
  await unregister(keyStr.value)
  await register(keyStr.value, triggere)
  pervKeyStr.value = keyStr.value
}
const triggere = debounce(() => {
  onClick()
}, 200)
const keyStr = ref("F8");
const pervKeyStr = ref("");
const onBlur = async () => {
  await unregister(pervKeyStr.value)
  await unregister(keyStr.value)
  await register(keyStr.value, triggere)
  pervKeyStr.value = keyStr.value
}
const greetMsg = ref("");
const name = ref("");
const starting = ref(false);
const random = ref([200, 300])
const intervalNum = ref(getRandom(random.value[0], random.value[1]))
const btnText = ref('开始');
async function greet() {
  // Learn more about Tauri c1ommands at https://tauri.app/develop/calling-rust/
  greetMsg.value = await invoke("greet", { name: name.value });
}
const onClick = () => {
  console.log('onClick')
  if (starting.value) {
    btnText.value = '开始'
    starting.value = false
  } else {
    starting.value = true
    btnText.value = '停止'
    clickInterval()
  }
}
const clickInterval = async () => {
  if (!starting.value) {
    return
  }
  intervalNum.value = getRandom(Number(random.value[0]), Number(random.value[1]))
  await sleep(intervalNum.value)
  // await invoke("auto_click");
  await autoClick()
  console.log('auto_click')
  await clickInterval()
}
</script>

<template>
  <div class="auto-click">
    <div class="key">
      <Input v-model="keyStr" @blur="onBlur" />
    </div>
    <Input v-model="random[0]" /> - <Input v-model="random[1]" />
    <div class="btn">
      <Button @click="onClick" :theme="starting ? 'warn' : ''" block>{{ btnText }}</Button>
    </div>
  </div>
</template>

<style scoped lang="less">
.auto-click {
  text-align: center;
  margin: 0 auto;
}

.key {
  display: flex;
  margin-bottom: 20px;

  .input {
    width: 100%;
  }
}

.btn {
  margin: 20px auto;
  width: 300px;
}
</style>
